<?php

use ZEGO\ZegoServerAssistant;
use ZEGO\ZegoErrorCodes;


if(!function_exists('change_time_long')){
    function change_time_long($time) {

        if (is_numeric($time)) {

            $value = array(

                "days" => 0, "hours" => 0,
                "minutes" => 0, "seconds" => 0,
            );

            if ($time >= 86400) {

                $value["days"] = floor($time / 86400);

                $time = ($time % 86400);
            }

            if ($time >= 3600) {

                $value["hours"] = floor($time / 3600);
                $time = ($time % 3600);
            }

            if ($time >= 60) {

                $value["minutes"] = floor($time / 60);
                $time = ($time % 60);
            }

            $value["seconds"] = floor($time);

            if(strlen($value["hours"])<2 && $value["days"]==0){

                //$value["hours"]="0".$value["hours"];
            }else if(strlen($value["hours"])<2 && $value["days"]!=0){

                $value["hours"]=$value["days"] * 24 + $value["hours"];
            }else{

                $value["hours"]=$value["days"] * 24 + $value["hours"];
            }


            $t = $value["hours"] . "小时" . $value["minutes"] . "分" . $value["seconds"].'秒';

            Return $t;

        }

    }
}



if(!file_exists('GenerateSignature')){
    function generateSignature($appId, $signatureNonce, $serverSecret, $timestamp){

        $str = $appId.$signatureNonce.$serverSecret.$timestamp;
        $signature = md5($str);
        return $signature;

    }
}

//权限位定义
const PrivilegeKeyLogin   = 1; // 登录
const PrivilegeKeyPublish = 2; // 推流

//权限开关定义
const PrivilegeEnable     = 1; // 开启
const PrivilegeDisable    = 0; // 关闭

if(!function_exists('get_zego_token')){

    /**
     * 获得即构用户token
     * @param $roomId
     * @param $userId
     * @param $effectiveTimeInSeconds  // token有效时长 单位：秒
     * @return string
     */
    function get_zego_token($roomId = '', $userId = '', $effectiveTimeInSeconds = 86400)
    {
        $appId = config('zego.zego_appid');
        $serverSecret = config('zego.zego_server_secret');

        //权限位定义
        $privilegeKeyLogin   = 1; // 登录
        $privilegeKeyPublish = 2; // 推流

        $rtcRoomPayLoad = [
            'room_id' => $roomId, //房间id；用于对接口的房间id进行强验证
            'privilege' => [     //权限位开关列表；用于对接口的操作权限进行强验证
                $privilegeKeyLogin => 1,
                $privilegeKeyPublish => 1,
            ],
            'stream_id_list' => [] //流列表；用于对接口的流id进行强验证；允许为空，如果为空，则不对流id验证
        ];

        $payload = json_encode($rtcRoomPayLoad);

        $token = ZegoServerAssistant::generateToken04((int)$appId, $userId, $serverSecret, $effectiveTimeInSeconds, $payload);
        if ($token->code == ZegoErrorCodes::success) {
            return $token->token;
        } else {
            return '';
        }
    }
}

function img_url($url = '')
{
    if (strpos($url,'http://') !== false || strpos($url,'https://') !== false)
        return $url;
    return config('app.img_url') . $url;
}

if(!function_exists('rand_str')){
    function rand_str( $length = 4 )
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = array( 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
            'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x', 'y', 'z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' );
        // 在 $chars 中随机取 $length 个数组元素键名
        $keys = array_rand( $chars, $length );

        $password = '';
        for ( $i = 0; $i < $length; $i++ )
        {
            // 将 $length 个数组元素连接成字符串
            $password .= $chars[$keys[$i]];
        }
        return $password;
    }
}


if(!function_exists('get_video_cover')){

    /*
     * $streamPath 视频文件 或视频的缓存文件
     * $video_cover_name  视频截图名称   other/202200212/r32rfioj23nfiaof.jpg
     * $fromSecond   从第几秒开始截图
     */
    function get_video_cover($streamPath, $video_cover_name, $fromSecond = 1){

        $videoCover = App\Services\FFMpegUtil::getCover($streamPath, $video_cover_name,$fromSecond);

        return $videoCover;
    }
}


if(!function_exists('rand_string')){
    function rand_string( $length = 4 )
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = array( 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
            'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' );
        // 在 $chars 中随机取 $length 个数组元素键名
        $keys = array_rand( $chars, $length );

        $password = '';
        for ( $i = 0; $i < $length; $i++ )
        {
            // 将 $length 个数组元素连接成字符串
            $password .= $chars[$keys[$i]];
        }
        return $password;
    }
}



if(!function_exists('http_domain')){

    function http_domain($str,$domain){
        if(strpos($str,'http') !== false){
            return $str;
        }else{
            return $domain.$str;
        }
    }
}


if(!function_exists('jsonSuccess')){

    function jsonSuccess($data = [], $message = '', $code = '200', $error_code = '0000'){

        if(!$message || is_numeric($data)){
            $codes = file_get_contents('codes.json');
            $codes = json_decode($codes,true);
            if(is_numeric($data)){
                $error_code = intval($data);
            }
            $message = $codes[$error_code];
        }

        $datas = [
            'code' => $code,
            'error_code' => $error_code,
            'message' => $message,
            'data' => is_numeric($data) ? [] : $data
        ];


        return json_encode($datas,JSON_UNESCAPED_UNICODE);
    }
}


if(!function_exists('jsonError')){

    function jsonError($message = '', $error_code = 4000, $code = 400,  $data = []){


        if(!$message || is_numeric($message)){
            $codes = file_get_contents('codes.json');
            $codes = json_decode($codes,true);
            if(is_numeric($message)){
                $error_code = intval($message);
            }
            $message = $codes[$error_code];
        }

        $datas = [
            'code' => $code,
            'error_code' => $error_code,
            'message' => $message,
        ];

        if($data){
            $datas = array_merge($datas,['data' => $data]);
        }

        return json_encode($datas,JSON_UNESCAPED_UNICODE);
    }
}

if(!function_exists('jsonMove')){

    function jsonMove($code = '200', $error_code = '0000', $message = '', $data = []){

        if(!$message){
            $codes = file_get_contents('codes.json');
            $codes = json_decode($codes,true);
            $message = $codes[$error_code];
        }

        $datas = [
            'code' => $code,
            'error_code' => $error_code,
            'message' => $message,
            'data' => $data
        ];

        return json_encode($datas,JSON_UNESCAPED_UNICODE);
    }
}


/*
 * 随机字符串
 */
if(!function_exists('randStr'))
{
    function randStr()
    {
        return sprintf(
            '%04x%04x-%04x%04x-%04x-%04x%04x',
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff)
        );
    }
}


// 身份证号规则验证
function check_id_num($idnum = '')
{
    if (empty($idnum)) {
        return false;
    }
    if (strlen($idnum) == 15) {
        // 15位身份证号
        $isIDCard = '/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/';
    } elseif (strlen($idnum) == 18) {
        // 18位身份证号
        $isIDCard = '/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/';
    } else {
        return false;
    }

    if (preg_match($isIDCard, $idnum)) {
        return true;
    } else {
        return false;
    }
}

// 通过身份证获得出生时间
function get_idcard_info($IDCard)
{
    $result['status'] = 0;//0：未知错误，-1：身份证格式错误，1：无错误
    $result['flag'] = '';//0标示成年，1标示未成年
    $result['tdate'] = '';//生日，格式如：2012-11-15
    if (!check_id_num($IDCard)) {
        $result['status'] = -1;
        return $result;
    } else {
        if (strlen($IDCard)==18) {
            $tyear = intval(substr($IDCard,6,4));
            $tmonth = intval(substr($IDCard,10,2));
            $tday = intval(substr($IDCard,12,2));
            if ($tyear > date("Y") || $tyear < (date("Y") - 100)) {
                $flag = 0;
            } elseif ($tmonth < 0 || $tmonth > 12) {
                $flag = 0;
            } elseif ($tday < 0 || $tday > 31) {
                $flag = 0;
            } else {
                $tdate = $tyear."-".$tmonth."-".$tday;
                if ((time() - mktime(0,0,0,$tmonth,$tday,$tyear)) > 18*365*24*60*60) {
                    $flag = 0;
                }else{
                    $flag = 1;
                }
            }
        } elseif (strlen($IDCard) == 15) {
            $tyear = intval("19".substr($IDCard, 6, 2));
            $tmonth = intval(substr($IDCard, 8, 2));
            $tday = intval(substr($IDCard, 10, 2));
            if ($tyear > date("Y") || $tyear < (date("Y") - 100)) {
                $flag = 0;
            } elseif ($tmonth < 0 || $tmonth > 12) {
                $flag = 0;
            } elseif ($tday < 0 || $tday > 31) {
                $flag = 0;
            } else {
                $tdate = $tyear."-".$tmonth."-".$tday;
                if ((time() - mktime(0, 0, 0, $tmonth, $tday, $tyear)) > 18*365*24*60*60) {
                    $flag = 0;
                } else {
                    $flag = 1;
                }
            }
        }
    }
    $result['status'] = 1;
    $result['is_adult'] = $flag; // 0标示成年，1标示未成年
    $result['birthday'] = $tdate; // 生日日期
    $result['birthday_year'] = $tyear; // 生日年
    $result['birthday_month'] = $tmonth; // 生日月
    $result['birthday_day'] = $tday; // 生日日
    return $result;
}

// 时段名称替换
function replace_period($period = 'am')
{
    $periodName = '上午';
    if ($period == 'pm') {
        $periodName = '下午';
    }

    return $periodName;
}

/**
 * 判断是否为微信浏览器访问
 * @return bool
 */
function is_wechat_browser(){
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    if (strpos($user_agent, 'MicroMessenger') === false){
//        echo '非微信浏览器禁止浏览';
        return false;
    } else {
//        echo '微信浏览器，允许访问';
        //preg_match('/.*?(MicroMessenger\/([0-9.]+))\s*/', $user_agent, $matches);
        //echo '<br>你的微信版本号为:'.$matches[2];
        return true;
    }
}

/**
 * 按字节数截取标题
 */
function trunc_title($str, $byte, $dot='...')
{
    $len = 0;
    $strnew = '';

    // 循环字数
    for ($i=0; $i<mb_strlen($str); $i++) {
        // 截取一个字，utf-8必须加上否者会乱码
        $letter = mb_substr($str, $i, 1, 'utf-8');

        // 过滤沉淀
        if (empty($letter) && $letter != 0) continue;

        if (preg_match("/^[\x7f-\xff]+$/", $letter)) $len += 2;
        else $len += 1;

        // 超长
        if (($len+mb_strlen($dot)) > $byte) {
            $strnew .= $dot;
            break;
        }

        $strnew .= $letter;
    }
    return $strnew;
}

/**
 * 获得文件名称
 * @param string $file_path public_path('/uploads/XXXXXX.mp4');
 * @return string
 */
function get_file_name($file_path = '')
{
    $file_name = '';
    if ($file_path) {
        $info = pathinfo($file_path);
        $file_name = basename($file_path, '.'.$info['extension']);
    }
    return $file_name;
}

/**
 * 两个日期中间天数
 * @param $day1
 * @param $day2
 * @return float|int
 */
function diff_between_two_days ($day1, $day2)
{
    $second1 = strtotime($day1);
    $second2 = strtotime($day2);

    if ($second1 < $second2) {
        $tmp = $second2;
        $second2 = $second1;
        $second1 = $tmp;
    }
    return ($second1 - $second2) / 86400;
}


/**
 * ajax失败返回
 * @param string $message
 * @param int $code
 * @return array
 */
function ajaxError($message = '', $code = 0)
{
    if (empty($message)) {
        $message = '请求失败';
    }
    return ['status' => $code, 'info' => $message];
}

/**
 * ajax成功返回
 * @param string $message
 * @param array $data
 * @param string $url
 * @param int $code
 * @return array
 */
function ajaxSuccess($message = '', $data = array(), $url = '', $code = 1)
{
    if (empty($message)) {
        $message = '请求成功！';
    }
    return ['status' => $code, 'info' => $message, 'url' => $url, 'data' => $data];
}

?>